package cn.aiyuan.controller;

import cn.aiyuan.config.AliPayProperties;
import cn.aiyuan.mapper.AlipayMapper;
import cn.aiyuan.pojo.TradeOrder;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wy
 * @date 2020/6/16
 */
@Controller
@RequestMapping("/ali")
public class PayController {

    private final AliPayProperties aliPayProperties;

    private final AlipayMapper alipayMapper;

    public PayController(AliPayProperties aliPayProperties, AlipayMapper alipayMapper) {
        this.aliPayProperties = aliPayProperties;
        this.alipayMapper = alipayMapper;
    }

    @RequestMapping("/pay")
    @ResponseBody
    public void applyPay(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {

        //支付订单号
        String tradeNo = String.valueOf(new Date().getTime());

        //支付金额
        String amount = "88.88";

        //保存一个交易记录
        TradeOrder tradeOrder = new TradeOrder(
                tradeNo, //交易编号
                new BigDecimal(amount), //金额
                "购买Iphone6 16G支付", //备注
                TradeOrder.STATUS_PAYING_APPLY, //支付状态：支付中
                1L //支付的用户ID
        );
        alipayMapper.insert(tradeOrder);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                aliPayProperties.getUrl(),
                aliPayProperties.getAppId(),
                aliPayProperties.getAppPrivateKey(),
                aliPayProperties.getFormat(),
                aliPayProperties.getCharset(),
                aliPayProperties.getAlipayPublicKey(),
                aliPayProperties.getSignType());

        //创建API对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

        //同步回调地址
        alipayRequest.setReturnUrl("http://es9z8x.natappfree.cc/ali/payReturn");

        //异步回调地址
        alipayRequest.setNotifyUrl("http://es9z8x.natappfree.cc/ali/payNotify");

        //封装请求参数
        Map<String,String> bizContent = new HashMap<>();
        bizContent.put("out_trade_no",tradeNo);
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
        bizContent.put("total_amount",amount);
        bizContent.put("subject","Iphone6 16G");
        bizContent.put("body","Iphone6 16G");

        //请求的数据
        alipayRequest.setBizContent(JSON.toJSONString(bizContent));

        //调用SDK生成表单
        String form = alipayClient.pageExecute(alipayRequest).getBody();

        httpResponse.setContentType("text/html;charset=" + aliPayProperties.getCharset());
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    //支付同步回调
    @RequestMapping("payReturn")
    @ResponseBody
    public String payReturn(HttpServletRequest request){
        System.out.println("payReturn==============================");
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()){
            System.out.println(parameterNames.nextElement());
        }


        return "cn.aiyuan.controller.PayController.payReturn";
    }

}
